<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/cookie.js"></script>
</head>

<body>
    <button class="edit">修改</button>
    <button class="del">删除</button>
</body>
<script>
    // cookie的修改
    // cookie修改 是根据键名(key) 修改对应的值(重新根据键名赋值即可)

    // cookie的删除
    // 1. 手动删除  => 测试代码
    // 2. 把cookie的过期时间设置为已经过去的时间  (cookie过期之后 浏览器无法读取,但是在地址栏中还可以手动 => 浏览器刷新)


    var edit = document.getElementsByClassName("edit")[0];
    var del = document.getElementsByClassName("del")[0];

    edit.onclick = function () {
        // 存储用户名 密码  手机号 邮箱 (此处案例需要)

        setCookie("user", "b123123", 14);
        setCookie("pwd", "321321", 14);

    }


    del.onclick = function () {

        // 把cookie的过期时间设置为已经过去的时间
        // setCookie("user", "", -1);
        // setCookie("pwd", "", -1);
        // setCookie("phone", "", -1);
        // setCookie("email", "", -1);

        // 单删
        // deleteCookie("user");
        // deleteCookie("pwd");
        // deleteCookie("phone");
        // deleteCookie("email");

        clearCookie();

        location.reload();
        console.log(document.cookie);
    }


    // var m = new Map()
    // m.set(key,val)
    // m.get(key)
    // m.delete(key)
    // m.clear()

    function setCookie(key, val, day, path = "/") {
        if (day != undefined) {  // 有参数 => 设置过期时间 
            var date = new Date();
            date.setDate(date.getDate() + day);
            document.cookie = key + "=" + val + ";expires=" + date.toUTCString() + ";path=" + path;
        } else {  // 没有参数day  => 默认浏览器关闭过期
            document.cookie = key + "=" + val + ";path=" + path;
        }
    }



    function getCookie(key) {
        var cookie = document.cookie;
        if (cookie) {
            var list = cookie.split("; ");
            // console.log(list);
            for (var i = 0; i < list.length; i++) {
                var item = list[i];  // 'user=a123123', 'pwd=123123'
                var attr = item.split("=")[0];
                var val = item.split("=")[1];

                // 每次解析之后判断 
                if (key === attr) {
                    return val;
                }

            }
        }
        return "";
    }


    function deleteCookie(key) {
        setCookie(key, "", -1);
    }

    function clearCookie() {
        var cookie = document.cookie;
        if (cookie) {
            var list = cookie.split("; ");
            // console.log(list);
            for (var i = 0; i < list.length; i++) {
                var item = list[i];  // 'user=a123123', 'pwd=123123'
                var attr = item.split("=")[0];
                var val = item.split("=")[1];
                delete (attr);
            }
        }
    }

</script>

</html>